package com.zhuhjay.c1;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;

import static com.zhuhjay.util.ByteBufferUtil.debugRead;

/**
 * @author ZhuHJay
 * @date 2023/3/1 21:13
 */
@SuppressWarnings("all")
public class MultiThreadServer {

    public static void main(String[] args) throws IOException {
        new BossEvenLoop().register(2);
    }

    @Slf4j
    static class BossEvenLoop implements Runnable {
        private Selector boss;
        private Worker[] workers;
        private volatile boolean start;
        private AtomicInteger index = new AtomicInteger();

        public void register(int workersCapacity) throws IOException {
            if (!start) {
                ServerSocketChannel ssc = ServerSocketChannel.open();
                ssc.configureBlocking(false);
                ssc.bind(new InetSocketAddress(8080));
                log.info("starter server");
                boss = Selector.open();
                ssc.register(boss, SelectionKey.OP_ACCEPT);
                workers = initWorkers(workersCapacity);
                new Thread(this, "boss").start();
                start = true;
            }
        }

        /** 初始化工作线程 **/
        private Worker[] initWorkers(int capacity) {
            Worker[] result = new Worker[capacity];
            for (int i = 0; i < capacity; i++) {
                result[i] = new Worker("worker-" + i);
            }
            return result;
        }

        @Override
        @SneakyThrows
        public void run() {
            while (true) {
                boss.select();
                Iterator<SelectionKey> itr = boss.selectedKeys().iterator();
                while (itr.hasNext()) {
                    SelectionKey key = itr.next();
                    itr.remove();
                    if (key.isAcceptable()) {
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        SocketChannel sc = channel.accept();
                        sc.configureBlocking(false);
                        log.info("register sc: {}", sc.getRemoteAddress());
                        // 使用轮询算法来进行负载均衡
                        workers[index.getAndIncrement() % workers.length].register(sc);
                    }
                }
            }
        }
    }

    @Slf4j
    static class Worker implements Runnable {
        private String name;
        private Selector selector;
        private volatile boolean start;
        private ConcurrentLinkedDeque<Runnable> deque = new ConcurrentLinkedDeque<>();

        public Worker(String name) {
            this.name = name;
        }

        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                selector = Selector.open();
                new Thread(this, name).start();
                start = true;
            }
            deque.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();
        }

        @Override
        @SneakyThrows
        public void run() {
            while (true) {
                selector.select();
                Runnable poll = deque.poll();
                if (poll != null) {
                    poll.run();
                }
                Iterator<SelectionKey> itr = selector.selectedKeys().iterator();
                while (itr.hasNext()) {
                    SelectionKey key = itr.next();
                    itr.remove();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(64);
                        log.info("read sc: {}", channel.getRemoteAddress());
                        try {
                            int read = channel.read(buffer);
                            if (read == -1) {
                                // 连接正常断开时需要取消事件
                                key.cancel();
                            } else {
                                buffer.flip();
                                debugRead(buffer);
                            }
                        } catch (IOException e) {
                            // 连接异常断开时需要取消事件
                            key.cancel();
                        }
                    }
                }
            }
        }
    }

}
